package 水果成篮;

import java.util.HashMap;

class Solution {
    //利用HashMap求解
    public int totalFruit(int[] fruits) {
        int count = 0;
        int left = 0;
        int right = 0;
        HashMap<Integer,Integer> map = new HashMap<>();
        int n = fruits.length;
        while (right < n){
            map.put(fruits[right],map.getOrDefault(fruits[right],0) + 1);
            while (map.size() > 2){
                map.put(fruits[left],map.get(fruits[left]) - 1);
                if (map.get(fruits[left]) == 0){
                    map.remove(fruits[left]);
                }
                left++;
            }
            count = Math.max(count,right - left + 1);
            right++;
        }
        return count;
    }

    //利用数组代替HashMap进行求解
    public int totalFruit1(int[] fruits) {
        int count = 0;
        int left = 0;
        int right = 0;
        int kinds = 0;
        int n = fruits.length;
        int[] hash = new int[n + 1];
        while (right < n){
            if(hash[fruits[right]] == 0){
                kinds++;
            }
            hash[fruits[right]]++;
            while (kinds > 2){
                hash[fruits[left]]--;
                if (hash[fruits[left]] == 0){
                    kinds--;
                }
                left++;
            }
            count = Math.max(count,right - left + 1);
            right++;
        }
        return count;
    }
}